<template>
    <div class="flex min-h-screen bg-gray-100 dark:bg-gray-900 transition-colors duration-300">
        <!-- 主内容区域 -->
        <div class="ml-0 flex flex-1">
            <!-- 图片墙 -->
            <div class="flex-1 overflow-y-auto p-4">
                <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-4">
                    <div v-for="(img, index) in imgList" :key="img"
                        class="relative overflow-hidden rounded-lg shadow-lg cursor-pointer" @click="showImage(index)">
                        <img :src="img" alt="shishi"
                            class="w-full h-64 object-cover transition-transform duration-300 hover:scale-105" />
                    </div>
                </div>
                <!-- 懒加载触发器 -->
                <div ref="sentinel" class="h-4 w-full"></div>
            </div>

            <!-- 大图展示区域 -->
            <div v-if="selectedIndex !== null"
                class="w-1/3 h-screen sticky top-0 p-4 bg-gray-200 dark:bg-gray-800 flex flex-col items-center justify-center">
                <div class="relative w-full">
                    <img :src="imgList[selectedIndex]" alt="shishi"
                        class="w-full h-auto object-contain rounded-lg shadow-lg" @click="closeImage" />
                    <!-- 左箭头按钮 -->
                    <button @click="prevImage"
                        class="absolute top-1/2 left-4 transform -translate-y-1/2 bg-black bg-opacity-30 text-white w-10 h-10 rounded-full flex items-center justify-center hover:bg-opacity-50 transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                            stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                        </svg>
                    </button>
                    <!-- 右箭头按钮 -->
                    <button @click="nextImage"
                        class="absolute top-1/2 right-4 transform -translate-y-1/2 bg-black bg-opacity-30 text-white w-10 h-10 rounded-full flex items-center justify-center hover:bg-opacity-50 transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                            stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                        </svg>
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'

const imgList = reactive<string[]>([])
const selectedIndex = ref<number | null>(null)
const loading = ref(false)
const hasMore = ref(true)
const sentinel = ref<HTMLElement | null>(null)
let observer: IntersectionObserver | null = null

// 获取图片
async function getIMG() {
    if (loading.value || !hasMore.value) return
    loading.value = true

    try {
        const result = await axios.get('http://127.0.0.1:8000/random_images')
        const urls: string[] = result.data.message

        // 去重
        urls.forEach(url => {
            if (!imgList.includes(url)) {
                imgList.push(url)
            }
        })

        if (urls.length < 10) {
            hasMore.value = false
        }
    } catch (e) {
        console.error('图片加载失败', e)
        hasMore.value = false
    } finally {
        loading.value = false
    }
}

// 大图控制
function showImage(index: number) {
    selectedIndex.value = index
}

function closeImage() {
    selectedIndex.value = null
}

function prevImage() {
    if (selectedIndex.value !== null) {
        selectedIndex.value = (selectedIndex.value - 1 + imgList.length) % imgList.length
    }
}

function nextImage() {
    if (selectedIndex.value !== null) {
        selectedIndex.value = (selectedIndex.value + 1) % imgList.length
    }
}

// 懒加载观察器
function setupObserver() {
    observer = new IntersectionObserver(async (entries) => {
        if (entries[0].isIntersecting) {
            await getIMG()
        }
    })

    if (sentinel.value) {
        observer.observe(sentinel.value)
    }
}

onMounted(async () => {
    await getIMG() // 初始加载
    setupObserver()
    window.addEventListener('keydown', handleKeydown)
})

onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleKeydown)
    if (observer && sentinel.value) {
        observer.unobserve(sentinel.value)
    }
})


function handleKeydown(e: KeyboardEvent) {
    if (selectedIndex.value !== null) {
        if (e.key === 'ArrowLeft') {
            prevImage()
        }
        else if (e.key === 'ArrowRight') {
            nextImage()
        }
        else if (e.key === 'Home') {
            selectedIndex.value = 0
        } else if (e.key === 'End') {
            selectedIndex.value = imgList.length - 1
        }
    }
}


</script>